package com.yingcheng.numerology.framework.bazi.core.calculator;

import com.yingcheng.numerology.framework.bazi.core.util.BaZiUtil;
import com.yingcheng.numerology.framework.bazi.core.vo.AbstractParameter;
import com.yingcheng.numerology.framework.bazi.core.vo.YearPillarCalculatorRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 年柱计算
 *
 * @author xiaofeng
 * @date 2025/1/12 18:16
 */
public class YearPillarCalculatorHandler extends AbstractCalculatorHandler<String, AbstractParameter> {

    /**
     * TODO 需要动态获取,从数据库中获取
     */
    // 立春时间映射表
    private static final Map<Integer, String> LICHUN_MAP = new HashMap<>();

    static {
        // 示例：2023年、2024年和2025年的立春时间
        LICHUN_MAP.put(1986, "1986-02-04T10:42:00");
        LICHUN_MAP.put(2023, "2023-02-04T10:42:00");
        LICHUN_MAP.put(2024, "2024-02-04T16:22:00");
        LICHUN_MAP.put(2025, "2025-02-04T22:04:00");
    }

    @Override
    public String calculatorHandler(AbstractParameter parameter) {
        if (!(parameter instanceof YearPillarCalculatorRequest)) {
            throw new IllegalArgumentException("对象转换错误");
        }
        YearPillarCalculatorRequest yearPillarCalculatorRequest = (YearPillarCalculatorRequest) parameter;
        LocalDateTime birthDateTime = LocalDateTime.of(yearPillarCalculatorRequest.getYear(),
                yearPillarCalculatorRequest.getMonth(), yearPillarCalculatorRequest.getDay(),
                yearPillarCalculatorRequest.getHour(), yearPillarCalculatorRequest.getMinute());
        return this.calculateYearPillar(birthDateTime, yearPillarCalculatorRequest.getLichunDateTime());
    }

    public String calculateYearPillar(LocalDateTime birthDateTime, LocalDateTime lichunDateTime) {
        // 获取出生年份
        int year = birthDateTime.getYear();
//        LocalDateTime lichunDateTime = getLichunDateTime(year);

        // 判断是否属于农历上一年
        if (birthDateTime.isBefore(lichunDateTime)) {
            year--; // 立春之前属于上一年
        }
        return BaZiUtil.calculateYearHeavenlyStems(year, true);
    }

    /**
     * 获取指定年份的立春时间
     *
     * @param year 公历年份
     * @return 立春时间（LocalDateTime）
     */
    public LocalDateTime getLichunDateTime(int year) {
        if (LICHUN_MAP.containsKey(year)) {
            return LocalDateTime.parse(LICHUN_MAP.get(year), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }
        throw new IllegalArgumentException("未定义该年份的立春时间: " + year);
    }
}
